import {
    AnyAction,
    ThunkDispatch,
    autoBatchEnhancer,
    combineReducers,
    configureStore,
  } from '@reduxjs/toolkit';
  import systemReducer from 'features/system/store/systemSlice';
import generationReducer from 'features/parameters/store/generationSlice';
import configReducer from 'features/system/store/configSlice';
import questionReducer from 'features/question/store/questionSlice';
import galleryReducer from 'features/gallery/store/gallerySlice';

  import dynamicMiddlewares from 'redux-dynamic-middlewares';
  import { api } from 'services/api';
  import { listenerMiddleware } from './middleware/listenerMiddleware';
  import { $store } from './nanostores/store';
  
  const allReducers = {
    system: systemReducer,
    generation: generationReducer,
    config: configReducer,
    gallery: galleryReducer,
    question: questionReducer,
    [api.reducerPath]: api.reducer,
  };
  
  const rootReducer = combineReducers(allReducers);
  
  export const store = configureStore({
    reducer: rootReducer,
    enhancers: (existingEnhancers) => {
      return existingEnhancers
        .concat(autoBatchEnhancer());
    },
    middleware: (getDefaultMiddleware) =>
      getDefaultMiddleware({
        serializableCheck: false,
        immutableCheck: false,
      })
        .concat(api.middleware)
        .concat(dynamicMiddlewares)
        .prepend(listenerMiddleware.middleware),
    devTools: {
      trace: true,
    },
  });
  
  export type AppGetState = typeof store.getState;
  export type RootState = ReturnType<typeof store.getState>;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  export type AppThunkDispatch = ThunkDispatch<RootState, any, AnyAction>;
  export type AppDispatch = typeof store.dispatch;
  export const stateSelector = (state: RootState) => state;
  $store.set(store);
  